const { BrowserWindow, dialog, ipcMain } = require("electron");
const mTool = require('../Tool/mTool');
const path = require('path');
const mEmitter = require("../Manager/eventEmitter");
const mFileTool = require("../Tool/mFileTool");

let filePaths;//线路文档的路径容器
let fileNames;//线路文档的文件名容器
let routeIDs;//线路ID的容器
let fileNamesIndex = 0;//文件名容器的索引对象

let routeType, routeArea, routeAbbreviation;//线路ID的初始信息


let createRouteID = null;//打开"共享系统"窗口
let optionWindow = null;
function createWindow() {
    createRouteID = new BrowserWindow({
        x: 100,
        y: 10,
        width: 1300,
        height: 900,
        alwaysOnTop: true,
        show: false,
        autoHideMenuBar: true,
        backgroundColor: '#f0ffff',
        title: "生成线路ID",
        webPreferences: {
            // nodeIntegration: true
            preload: path.join(__dirname, '/script/createRouteID_preload.js')
        }
    });

    createRouteID.once('ready-to-show', () => {
        createRouteID.show();
    });

    createRouteID.on('closed', () => {
        createRouteID = null;
        mEmitter.emit("displayMainWindow");
    });

    createRouteID.loadURL("https://yxly.vilives.com/login?redirect=%2Findex");

    // createRouteID.webContents.openDevTools();

    createRouteID.webContents.on('did-finish-load', () => {
        let webTitle = createRouteID.webContents.getTitle();
        if (webTitle === '共享管理系统') {
            mTool.addScript2Web(createRouteID.webContents, path.join(__dirname, 'script/createRouteID_Web.js'));
        }
        // createRouteID.webContents.executeJavaScript('document.getElementById("tab-uname").innerText').then(data => {
        //     console.log(data);
        //     webContentSign = data;
        //     if (webTitle === '共享管理系统' && webContentSign === '账号密码登录') {
        //         console.log('自动登录');
        //         mTool.addScript2Web(createRouteID.webContents, path.join(__dirname, 'script/autoLoginGX_Sys.js'));
        //     } else if (webTitle === '共享管理系统' && !(webContentSign === '账号密码登录')) {
        //         console.log('主页');
        //     }
        // })
    });
}

function createOptionWindow() {
    optionWindow = new BrowserWindow({
        x: 100,
        y: 10,
        width: 600,
        height: 500,
        alwaysOnTop: true,
        show: false,
        autoHideMenuBar: true,
        backgroundColor: '#f0ffff',
        title: "设置线路ID的基础信息",
        webPreferences: {
            // nodeIntegration: true
            preload: path.join(__dirname, '/script/createRouteID_Option_preload.js')
        }
    });
    optionWindow.once('ready-to-show', () => {
        optionWindow.show();
    });

    optionWindow.on('closed', () => {
        optionWindow = null;
        mEmitter.emit("displayMainWindow");
    });

    optionWindow.loadFile(path.join(__dirname, '/createRouteID_Option.html'));

    //选择需要生成线路ID的文档
    filePaths = mFileTool.openFileSelectorSync(createRouteID)
    fileNames = [];
    routeIDs = [];
    if (filePaths == null) {
        mEmitter.emit("displayMainWindow");
        createRouteID.close();
        return;
    }
    //去除文件名的'返佣'和'后缀'
    for (const filePath of filePaths) {
        let fileName = path.basename(filePath, path.extname(filePath));
        fileName = fileName.replace(/\w+(-\w+)+/, "");
        fileNames.push(fileName);
    }

    console.log(fileNames);
}

//*******************进程间通信******************/
//返回线路名称给'线路ID生成界面'
ipcMain.handle('getFileName', (event) => {
    if (fileNamesIndex < fileNames.length) {
        return fileNames[fileNamesIndex++];
    } else {
        //持久化'线路ID'
        let routeID_text = "";
        for (const routeID of routeIDs) {
            routeID_text += routeID + "\n";
        }
        require('fs').writeFileSync(path.join(path.dirname(filePaths[0]), 'ID.txt'), routeID_text);
        return null;
    }
});
//返回线路名称给'信息设置界面'
ipcMain.handle('getRouteName_option', (event) => {
    return fileNames[0];
});
//
ipcMain.handle('getRouteInfo', (event) => {
    return [routeType, routeArea, routeAbbreviation]
})
//获取'信息设置界面'的线路ID初始信息
ipcMain.on('start', (event, _routeType, _routeArea, _routeAbbreviation) => {
    routeType = _routeType;
    routeArea = _routeArea;
    routeAbbreviation = _routeAbbreviation;
    console.log(routeType, routeArea, routeAbbreviation);
    createWindow();//打开"共享系统"窗口
    if (optionWindow) {
        optionWindow.close();
    }
})
//保存线路ID到容器中
ipcMain.on('saveRouteID', (event, routeID) => {
    routeIDs.push(routeID);
})

module.exports = {
    createOptionWindow
}